package backend.cms.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;

import core.cms.model.Block;
import core.util.HibernateCoreUtil;

public class CmsManager extends HibernateCoreUtil{
	
	public Block addBlock(Block b)
	{
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(b);
		session.getTransaction().commit();
		return b;
	}
	public Block getBlockByUuid(Long uuid)
	{
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Block b = (Block) session.get(Block.class, uuid);
		session.getTransaction().commit();
		return b ;
	}
	public Block updateBlock(String content,String identifier,Long uuid)
	{
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Block block=(Block)session.get(Block.class, uuid);
		block.setContent(content);
		block.setIdentifier(identifier);
		session.update(block);
		session.getTransaction().commit();
		
		return block;
	}
	
	public void deleteBlockContent(Block block)
	{
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.delete(block);
		//session.delete(block);
		session.getTransaction().commit();
	}
	public Block getBlockByIdentifier(String identifier)
	{
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		 List <Block> bist = session.createQuery("from Block b where b.identifier='"+identifier+"'").list();
		 Iterator<Block> bitr = null ;
		 Block b = null ;
		 if(bist != null)
		 {
			 bitr = bist.iterator();
			 while(bitr.hasNext())
			 {
				 b = bitr.next() ;
			 }
		 }
		session.getTransaction().commit();
		
		return b;
	}
	
	public List<Block> getCmsList()
	{
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List <Block> block = session.createQuery("from Block").list();	
		session.getTransaction().commit();
		return block ;
	}
	
	public List<String> getAllBlock()
	{
		List<String> lstidentifier = new ArrayList<String>();
		Block b = null ;
		Session session = HibernateCoreUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Iterator <Block> allbist = session.createQuery("from Block").iterate();
			while(allbist.hasNext())
			{
				b = allbist.next() ;
				lstidentifier.add(b.getIdentifier());
			}
		 
		session.getTransaction().commit();
		
		return lstidentifier;
	}
}
